package com.example.oneSpringMVC.service.impl;

import com.example.oneSpringMVC.common.PageResult;
import com.example.oneSpringMVC.dto.RoleDto;
import com.example.oneSpringMVC.entity.Role;
import com.example.oneSpringMVC.mapper.RoleMapper;
import com.example.oneSpringMVC.mapper.RolePermissionMapper;
import com.example.oneSpringMVC.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xinTong
 * @since 2024-01-24
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 角色分页查询
     * @param pageQuery
     * @return
     */
    @Override
    public PageResult list(int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);

        Page<Role> page = roleMapper.list();

        PageResult result = new PageResult();
        result.setList(page);
        result.setTotal(page.getTotal());
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);

        return result;
    }

    /**
     * 查询所有角色
     * @return
     */
    @Override
    public List<Role> listAll() {
        List<Role> list = roleMapper.listAll();
        return list;
    }

    /**
     * 删除角色信息
     * @param roleId
     * @return
     */
    @Override
    public void delete(Long roleId) {
        // 角色删除后，角色权限关联表也应该删除相应权限
        roleMapper.deleteByRoleId(roleId);
        roleMapper.deleteByPermissionId(roleId);
    }

    @Override
    public Role info(Long roleId) {

       Role role = roleMapper.info(roleId);
        return role;
    }


    @Override
    public List<Role> query(Long employeeId) {

        List<Role> list = roleMapper.query(employeeId);

        return list;
    }

    @Override
    public void saveOrUpdate(RoleDto roleDto) {
        Role role = roleDto.getRole();

        List<Integer> permissionIds = roleDto.getPermissionIds();

        // 更新
        if (role.getId() != null){
            roleMapper.updateByRoleId(role);
            // 先删，后填
            rolePermissionMapper.deleteByRoleId(role.getId());

            for (Integer permissionId : permissionIds) {
                rolePermissionMapper.addByRoleId(role.getId(), permissionId);
            }
        }
        // 新增
        else {
            roleMapper.insert(role);
            Long roleId = role.getId();

            for (Integer permissionId : permissionIds) {
                rolePermissionMapper.addByRoleId(roleId, permissionId);
            }
        }
    }
}
